package cn.zebra.dev.shop.module.revenue.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.order.module.item.entity.OrdersItemEntity;
import cn.zebra.dev.order.module.item.service.OrdersItemService;
import cn.zebra.dev.order.module.order.entity.OrdersEntity;
import cn.zebra.dev.order.module.order.service.OrdersService;
import cn.zebra.dev.other.module.shopRevenue.entity.ShopRevenueEntity;
import cn.zebra.dev.other.module.shopRevenue.service.ShopRevenueService;
import cn.zebra.dev.other.module.shopapply.entity.ShopApplyEntity;
import cn.zebra.dev.other.module.shopapply.service.ShopApplyService;
import cn.zebra.dev.product.module.sku.entity.ProductSkuEntity;
import cn.zebra.dev.product.module.sku.service.ProductSkuService;
import cn.zebra.dev.shop.module.revenue.dto.RevenueAddDTO;
import cn.zebra.dev.shop.module.revenue.dto.RevenueDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "店铺盈收管理")
@RequestMapping("/revenue")
public class RevenueController {

    @Autowired
    private ShopRevenueService shopRevenueService;

    @Autowired
    private ShopApplyService shopApplyService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrdersItemService ordersItemService;

    @Autowired
    private ProductSkuService productSkuService;

    @GetMapping("/list/{shopId}")
    @ApiOperation("店铺盈收列表")
    public Result<PageUtils<RevenueDTO>> list(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @PathVariable Long shopId) {
        Map<String, Object> params = new HashMap<>();
        params.put("shopId", shopId);
        params.put("limit", limit);
        params.put("page", page);
        PageUtils<ShopRevenueEntity> pageUtils = shopRevenueService.findPageByShopId(params);
        PageUtils<RevenueDTO> data = new PageUtils<>(pageUtils);
        List<ShopRevenueEntity> list = pageUtils.getList();
        if (list.size() > 0) {
            List<RevenueDTO> dtoList = new LinkedList<>();
            list.forEach(entity -> {
                RevenueDTO dto = new RevenueDTO();
                BeanUtils.copyProperties(entity, dto);
                dtoList.add(dto);
            });
            data.setList(dtoList);
        }
        return Result.success(data);
    }

    @GetMapping("/get/{shopId}")
    @ApiOperation("获取店铺盈利信息")
    public Result<RevenueAddDTO> get(@PathVariable Long shopId, @RequestParam("day") Integer day) {
        RevenueAddDTO dto = new RevenueAddDTO();
        //根据店铺id查出保证金
        ShopApplyEntity applyEntity = shopApplyService.selectOne("shop_id={0} and state=1", shopId);
        if (applyEntity == null) {
            return Result.error("该店铺没有注册申请信息，无法查看！！");
        }
        dto.setMargin(applyEntity.getMargin());
        //根据店铺id 查出店铺订单数量
        Integer orderCount = ordersService.count("shop_id = {0} and DATE_SUB(CURDATE(), INTERVAL {1} DAY) <= DATE(pay_time)", shopId, day);
        dto.setOrderCount(orderCount);
        List<OrdersEntity> orders = ordersService.selectList("shop_id = {0} and DATE_SUB(CURDATE(), INTERVAL {1} DAY) <= DATE(pay_time)", shopId, day);
        List<Long> ids = orders.stream().map(OrdersEntity::getId).collect(Collectors.toList());
        List<OrdersItemEntity> ordersItemEntities = ordersItemService.findByOrderIds(ids);
        BigDecimal ying = new BigDecimal(0);
        BigDecimal zhi = new BigDecimal(0);
        List<Long> productSkuIds = ordersItemEntities.stream().map(OrdersItemEntity::getProductSkuId).collect(Collectors.toList());
        List<ProductSkuEntity> productSkuEntities = productSkuService.findByIds(productSkuIds);
        for (OrdersItemEntity entity : ordersItemEntities) {
            ying = ying.add(entity.getTotalPrice());
            Optional<ProductSkuEntity> productSkuOptional = productSkuEntities.stream().filter(productSkuEntity -> productSkuEntity.getId().equals(entity.getProductSkuId())).findAny();
            if (productSkuOptional.isPresent()) {
                ProductSkuEntity productSkuEntity = productSkuOptional.get();
                zhi = zhi.add(productSkuEntity.getCostPrice().multiply(BigDecimal.valueOf(entity.getNum())));
            }
        }
        dto.setOrderMoney(ying);
        List<ShopRevenueEntity> shopRevenueEntities1 = shopRevenueService.selectList("shop_id={0} and revenue_type=3 and DATE_SUB(CURDATE(), INTERVAL {1} DAY) <= DATE(create_time)", shopId, day);
        for (ShopRevenueEntity entity : shopRevenueEntities1) {
            dto.setWithdrawMoney(dto.getWithdrawMoney().add(entity.getMoney()));
        }
        dto.setMoney(ying.subtract(zhi));
        return Result.success(dto);
    }
}
